package top.duorhs.jspider.output;

import cn.hutool.core.io.FileUtil;
import lombok.SneakyThrows;
import top.duorhs.jspider.constant.MarkDownUtil;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;

/**
 * @author Duorhs
 * @date 2023/1/11 13:27
 */
public class MarkdownFileWriter implements FileWriter {

    /**
     * 写入文件
     *
     * @param path    文件路径
     * @param content 内容
     */
    @Override
    @SneakyThrows
    public void write(String path, LinkedList<String> content) {
        String outputPath = FileUtil.mkdir(path).getAbsolutePath();
        //文件
        File file = new File(outputPath + File.separator + "result.md");
        if (file.exists()) {
            FileUtil.writeUtf8String("", file);
        }
        //图片目录
        FileUtil.mkdir(outputPath + File.separator + "images");
        for (String str : content) {
            if (str.startsWith("http")) {
                FileUtil.appendString(MarkDownUtil.buildMdImg(str) + "\n", file, StandardCharsets.UTF_8);
            } else {
                FileUtil.appendString(MarkDownUtil.buildMdLine(str) + "\n", file, StandardCharsets.UTF_8);
            }
        }
    }
}
